package com.zxy.service.v2;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zxy.dao.v2.TeacherDao;
import com.zxy.entity.v2.Teacher;
import okhttp3.*;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

/**
 * @Description: TODO
 * @Author: zhuxianyu
 * @Date: 2021/12/17 21:19
 * @Version: 1.0
 */
@Service
public class TeacherService {

    @Autowired
    TeacherDao teacherDao;

    public void httpRequest() {
        List<Teacher> teacherList = teacherDao.selectAll();
        JSONArray jsonArray = new JSONArray();
        jsonArray.addAll(teacherList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("teacherlist", jsonArray);
        sendData("http://127.0.0.1:8080/v2/save/student", jsonObject.toJSONString(), "");
    }

    /**
     * 向指定的url发送字符串数据
     * @param apiUrl
     * @param data
     * @param authKey
     */
    public static void sendData(String apiUrl, String data, String authKey) {
        System.out.println(data);
        OkHttpClient client = new OkHttpClient();
        client.dispatcher().setMaxRequestsPerHost(50);
        MediaType mediaType = MediaType.parse("application/json");
        try {
            RequestBody body = RequestBody.create(mediaType, data);
            Request.Builder builder = new Request.Builder()
                    .url(apiUrl)
                    .post(body)
                    .addHeader("Content-Type", "application/json");
            if ("" != authKey) {
                builder = builder.addHeader("authentication", authKey);
            }
            Request request = builder.build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    System.out.println("send data fail " + call.request().body().toString());
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    System.out.println("send data success");
                    response.close();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Send data end...");
        }
    }

//    /**
//     * 向指定的url发送字符串数据
//     *
//     * @param url
//     * @param data
//     * @return
//     */
//    public static void sendData(String path, String data) {
//        try {
//            // Configure and open a connection to the site you will send the request
//            URL url = new URL(path);
//            URLConnection urlConnection = url.openConnection();
//            // 设置doOutput属性为true表示将使用此urlConnection写入数据
//            urlConnection.setDoOutput(true);
//            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
////            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//            urlConnection.setRequestProperty("content-type", "application/json");
//            // 得到请求的输出流对象
//            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
//            // 把数据写入请求的Body
//            out.write(data);
//            out.flush();
//            out.close();
//
//            // 从服务器读取响应
//            InputStream inputStream = urlConnection.getInputStream();
//            String encoding = urlConnection.getContentEncoding();
//            String body = IOUtils.toString(inputStream, encoding);
//            System.out.println(body);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    /**
//     * 向指定的url发送字符串数据
//     *
//     * @param url
//     * @param data
//     * @return
//     */
//    public static String sendData(String url, String data) {
//        PrintWriter out = null;
//        BufferedReader in = null;
//        String result = "";
//        try {
//            URL realUrl = new URL(url);
//            // 打开和URL之间的连接
//            URLConnection conn = realUrl.openConnection();
//            // 设置通用的请求属性
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("Accept-Charset", "utf-8");
//            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("content-type", "application/json");
//            // 发送POST请求必须设置如下两行
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            // 获取URLConnection对象对应的输出流
//            out = new PrintWriter(conn.getOutputStream());
//            // 发送请求参数
//            out.print(data);
//            // flush输出流的缓冲
//            out.flush();
//            // 定义BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
//        } catch (Exception e) {
//            e.getMessage();
//        }
//        // 使用finally块来关闭输出流、输入流
//        finally {
//            try {
//                if (out != null) {
//                    out.close();
//                }
//                if (in != null) {
//                    in.close();
//                }
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//        return result;
//    }

}
